package linkedList.合并两个有序链表;

//将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
// 示例 1： 
//输入：l1 = [1,2,4], l2 = [1,3,4]
//输出：[1,1,2,3,4,4]
// 示例 2： 
//输入：l1 = [], l2 = []
//输出：[]
// 示例 3： 
//输入：l1 = [], l2 = [0]
//输出：[0]
// 提示： 
// 两个链表的节点数目范围是 [0, 50] 
// -100 <= Node.val <= 100 
// l1 和 l2 均按 非递减顺序 排列 
// Related Topics 递归 链表 👍 3812 👎 0
class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        /**
         * 双指针：currentl1 currentl2
         * 1,6,12,14
         * 5,6,7,20
         */
        if (null == list1) {
            return list2;
        }
        if (null == list2) {
            return list1;
        }
        ListNode current1 = list1;
        ListNode current2 = list2;
        ListNode ans = new ListNode(-1);
        ListNode ansC = ans;
        while (current1 != null || current2 != null) {
            if (current1 == null){
                ansC.next = current2;
                break;
            }
            if (current2 == null){
                ansC.next = current1;
                break;
            }
            if (current1.val < current2.val) {
                ansC.next = current1;
                current1 = current1.next;
                ansC = ansC.next;
            } else {
                ansC.next = current2;
                current2 = current2.next;
                ansC = ansC.next;
            }
        }
        return ans.next;
    }


    public static void main(String[] args) {
        //1,2,4
        ListNode list1 = new ListNode(1, new ListNode(2, new ListNode(4)));
        ListNode list2 = new ListNode(1, new ListNode(3, new ListNode(4)));
        Solution solution = new Solution();
        solution.mergeTwoLists(list1, list2);
    }
}
